package root.LocalityBasedLeastConnectionsScheduling;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

// 调度器类，负责调度请求
class Scheduler {

    private List<Server> servers;

    public Scheduler(List<Server> servers) {
        this.servers = servers;
    }

    // 选择最少连接且具有局部性匹配的服务器
    public Server scheduleRequest(Request request) {
        // 先筛选出满足局部性要求的服务器
        List<Server> localityServers = new ArrayList<>();
        for (Server server : servers) {
            if (server.getLocality().equals(request.getDataNeeded())) {
                localityServers.add(server);
            }
        }

        // 如果没有满足局部性要求的服务器，选择连接数最少的服务器
        if (localityServers.isEmpty()) {
            localityServers = new ArrayList<>(servers);
        }

        // 按照连接数升序排序
        localityServers.sort(Comparator.comparingInt(Server::getConnections));

        // 选择连接数最少的服务器
        Server selectedServer = localityServers.get(0);
        selectedServer.incrementConnections();

        return selectedServer;
    }

    // 任务完成后，减去连接数
    public void completeRequest(Server server) {
        server.decrementConnections();
    }
}

